package com.xiantm.study.thread.workthread;



public class Channel {

    private final WorkThread[] workThreadList;
    private final int MAX_REQUEST = 100;
    private int head;
    private int tail;
    private int count;
    private final Request[] requestQueue = new Request[MAX_REQUEST];
    private long startTime = 0 ;
    private long reqCount = 0;
    public Channel(int threadPool){
        workThreadList = new WorkThread[threadPool];
        for (int i = 0; i < threadPool; i++) {
            workThreadList[i] = new WorkThread("woker" + i, this);
        }
    }

    public  synchronized void putRequest(Request request){
        while (count >= requestQueue.length){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        requestQueue[tail] = request;
        tail = (tail+1) % requestQueue.length;
        count++;
        notifyAll();
    }



    public synchronized Request takeRequest(){
        while (count <= 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Request request = requestQueue[head];
        head = (head+1) % requestQueue.length;
        count--;
        return request;
    }

    public void startWorkers(){
        for (int i = 0; i < workThreadList.length; i++) {
            workThreadList[i].start();
        }
    }

}
